route.ts 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. BYTEDANCE_BASE_URL,
  4. ApiPath,
  5. ModelProvider,
  6. ServiceProvider,
  7. } from "@/app/constant";
  8. import { prettyObject } from "@/app/utils/format";
  9. import { NextRequest, NextResponse } from "next/server";
  10. import { auth } from "@/app/api/auth";
  11. import { isModelAvailableInServer } from "@/app/utils/model";
  12. const serverConfig = getServerSideConfig();
  13. async function handle(
  14. req: NextRequest,
  15. { params }: { params: { path: string[] } },
  16. ) {
  17. console.log("[ByteDance Route] params ", params);
  18. if (req.method === "OPTIONS") {
  19. return NextResponse.json({ body: "OK" }, { status: 200 });
  20. }
  21. const authResult = auth(req, ModelProvider.Doubao);
  22. if (authResult.error) {
  23. return NextResponse.json(authResult, {
  24. status: 401,
  25. });
  26. }
  27. try {
  28. const response = await request(req);
  29. return response;
  30. } catch (e) {
  31. console.error("[ByteDance] ", e);
  32. return NextResponse.json(prettyObject(e));
  33. }
  34. }
  35. export const GET = handle;
  36. export const POST = handle;
  37. export const runtime = "edge";
  38. export const preferredRegion = [
  39. "arn1",
  40. "bom1",
  41. "cdg1",
  42. "cle1",
  43. "cpt1",
  44. "dub1",
  45. "fra1",
  46. "gru1",
  47. "hnd1",
  48. "iad1",
  49. "icn1",
  50. "kix1",
  51. "lhr1",
  52. "pdx1",
  53. "sfo1",
  54. "sin1",
  55. "syd1",
  56. ];
  57. async function request(req: NextRequest) {
  58. const controller = new AbortController();
  59. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.ByteDance, "");
  60. let baseUrl = serverConfig.bytedanceUrl || BYTEDANCE_BASE_URL;
  61. if (!baseUrl.startsWith("http")) {
  62. baseUrl = `https://${baseUrl}`;
  63. }
  64. if (baseUrl.endsWith("/")) {
  65. baseUrl = baseUrl.slice(0, -1);
  66. }
  67. console.log("[Proxy] ", path);
  68. console.log("[Base Url]", baseUrl);
  69. const timeoutId = setTimeout(
  70. () => {
  71. controller.abort();
  72. },
  73. 10 * 60 * 1000,
  74. );
  75. const fetchUrl = `${baseUrl}${path}`;
  76. const fetchOptions: RequestInit = {
  77. headers: {
  78. "Content-Type": "application/json",
  79. Authorization: req.headers.get("Authorization") ?? "",
  80. },
  81. method: req.method,
  82. body: req.body,
  83. redirect: "manual",
  84. // @ts-ignore
  85. duplex: "half",
  86. signal: controller.signal,
  87. };
  88. // #1815 try to refuse some request to some models
  89. if (serverConfig.customModels && req.body) {
  90. try {
  91. const clonedBody = await req.text();
  92. fetchOptions.body = clonedBody;
  93. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  94. // not undefined and is false
  95. if (
  96. isModelAvailableInServer(
  97. serverConfig.customModels,
  98. jsonBody?.model as string,
  99. ServiceProvider.ByteDance as string,
  100. )
  101. ) {
  102. return NextResponse.json(
  103. {
  104. error: true,
  105. message: `you are not allowed to use ${jsonBody?.model} model`,
  106. },
  107. {
  108. status: 403,
  109. },
  110. );
  111. }
  112. } catch (e) {
  113. console.error(`[ByteDance] filter`, e);
  114. }
  115. }
  116. try {
  117. const res = await fetch(fetchUrl, fetchOptions);
  118. // to prevent browser prompt for credentials
  119. const newHeaders = new Headers(res.headers);
  120. newHeaders.delete("www-authenticate");
  121. // to disable nginx buffering
  122. newHeaders.set("X-Accel-Buffering", "no");
  123. return new Response(res.body, {
  124. status: res.status,
  125. statusText: res.statusText,
  126. headers: newHeaders,
  127. });
  128. } finally {
  129. clearTimeout(timeoutId);
  130. }
  131. }